package com.ruoyi.phoneController;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.domain.MobilOrder;
import com.ruoyi.service.IMobilOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 手机端订单Controller
 *
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/mobile/order")
public class MobilOrderController extends BaseController {
    @Autowired
    private IMobilOrderService mobilOrderService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody Map<String, Object> orderData) {
        try {
            // 解析订单信息
            MobilOrder order = new MobilOrder();
            order.setUserId((Integer) orderData.get("userId"));
            order.setVehicleId((Integer) orderData.get("vehicleId"));
            order.setStoreId((Integer) orderData.get("storeId"));
            order.setTypeId((Integer) orderData.get("typeId"));
            order.setRemark((String) orderData.get("remark"));
            order.setRepairMode((String) orderData.get("repairMode"));
            
            // 【修复】处理订单状态 - 使用前端传递的值
            if (orderData.get("orderStatus") != null) {
                order.setOrderStatus((Integer) orderData.get("orderStatus"));
                System.out.println("[ORDER-CREATE] Controller接收到的订单状态: " + orderData.get("orderStatus"));
            }
            
            // 处理预约时间
            if (orderData.get("appointTime") != null) {
                // 这里需要根据前端传递的时间格式进行解析
                // order.setAppointTime(...);
            }
            
            // 处理支付金额
            if (orderData.get("payAmount") != null) {
                order.setPayAmount(new BigDecimal(orderData.get("payAmount").toString()));
            }
            
            // 处理优惠券ID
            if (orderData.get("couponId") != null) {
                order.setCouponId((Integer) orderData.get("couponId"));
            }
            
            // 解析服务ID列表
            @SuppressWarnings("unchecked")
            List<Integer> serviceIds = (List<Integer>) orderData.get("serviceIds");
            
            int result = mobilOrderService.createOrder(order, serviceIds);
            if (result > 0) {
                // 构建明确的返回数据结构
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("orderNumber", order.getOrderNumber());
                resultData.put("orderId", order.getOrderId());
                resultData.put("status", "success");
                System.out.println("[ORDER-CREATE] Controller返回的订单号: " + order.getOrderNumber());
                System.out.println("[ORDER-CREATE] Controller返回的订单ID: " + order.getOrderId());
                return success(resultData);
            } else {
                return error("订单创建失败");
            }
        } catch (Exception e) {
            logger.error("创建订单失败", e);
            return error("订单创建失败：" + e.getMessage());
        }
    }

    /**
     * 支付订单
     */
    @PostMapping("/pay")
    public AjaxResult payOrder(@RequestBody Map<String, String> payData) {
        String orderNumber = payData.get("orderNumber");
        if (orderNumber == null || orderNumber.trim().isEmpty()) {
            return error("订单号不能为空");
        }
        
        try {
            int result = mobilOrderService.payOrder(orderNumber);
            if (result > 0) {
                return success("支付成功");
            } else {
                return error("支付失败");
            }
        } catch (Exception e) {
            logger.error("支付订单失败", e);
            return error("支付失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单号查询订单详情
     */
    @GetMapping("/detail/{orderNumber}")
    public AjaxResult getOrderDetail(@PathVariable String orderNumber) {
        MobilOrder order = mobilOrderService.getOrderCompleteInfo(orderNumber);
        if (order == null) {
            return error("订单不存在");
        }
        return success(order);
    }

    /**
     * 查询用户订单列表
     */
    @GetMapping("/user/{userId}")
    public AjaxResult getUserOrders(@PathVariable Integer userId) {
        List<MobilOrder> orders = mobilOrderService.selectOrdersByUserId(userId);
        return success(orders);
    }

    /**
     * 根据状态查询用户订单列表
     */
    @GetMapping("/user/{userId}/status/{status}")
    public AjaxResult getUserOrdersByStatus(@PathVariable Integer userId, @PathVariable Integer status) {
        List<MobilOrder> orders = mobilOrderService.selectOrdersByUserIdAndStatus(userId, status);
        return success(orders);
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel/{orderId}")
    public AjaxResult cancelOrder(@PathVariable Integer orderId) {
        try {
            int result = mobilOrderService.cancelOrder(orderId);
            if (result > 0) {
                return success("订单取消成功");
            } else {
                return error("订单取消失败");
            }
        } catch (Exception e) {
            logger.error("取消订单失败", e);
            return error("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 完成订单
     */
    @PostMapping("/complete/{orderId}")
    public AjaxResult completeOrder(@PathVariable Integer orderId) {
        try {
            int result = mobilOrderService.completeOrder(orderId);
            if (result > 0) {
                return success("订单完成");
            } else {
                return error("订单完成失败");
            }
        } catch (Exception e) {
            logger.error("完成订单失败", e);
            return error("完成订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单统计信息
     */
    @GetMapping("/statistics/user/{userId}")
    public AjaxResult getOrderStatistics(@PathVariable Integer userId) {
        // 查询各状态订单数量
        int waitingPayment = mobilOrderService.selectOrdersByUserIdAndStatus(userId, 0).size();
        int inProgress = mobilOrderService.selectOrdersByUserIdAndStatus(userId, 1).size();
        int completed = mobilOrderService.selectOrdersByUserIdAndStatus(userId, 2).size();
        int cancelled = mobilOrderService.selectOrdersByUserIdAndStatus(userId, 3).size();
        
        return success()
                .put("waitingPayment", waitingPayment)
                .put("inProgress", inProgress)
                .put("completed", completed)
                .put("cancelled", cancelled);
    }
}








